package cn.tedu.csmall.product.web;

import cn.tedu.csmall.product.ex.ServiceException;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

@Data
public class JsonResult<T> implements Serializable{
    /**
     * 业务状态码
     */
    @ApiModelProperty("业务状态码")
    private Integer state;
    /**
     * 操作失败时的提示文本
     */
    //@JsonInclude(JsonInclude.Include.NON_NULL)   //message为null时不显示节约资源
    @ApiModelProperty("操作失败时的提示文本")
    private String message;
    /**
     * 操作成功时的响应数据
     */
    @ApiModelProperty("操作成功时的响应数据")
    //private Object data;
    //T和上面<T>称泛型
    private T data;

    public JsonResult(){}

    public static JsonResult<Void> ok() {
        //重载可以用参数少的去调用参数多的
        //JsonResult jsonResult = new JsonResult();
        //jsonResult.state = ServiceCode.OK.getValue();
        //return jsonResult;
        return ok(null);
        //相当于
        //JsonResult jsonResult = new JsonResult();
        //jsonResult.state = ServiceCode.OK.getValue();
        //jsonResult.message = null;
        //jsonResult.data = null;
        //return jsonResult
    }

    //public static JsonResult ok(Object data) {
    public static <T> JsonResult<T> ok(T data) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.state = ServiceCode.OK.getValue();
        jsonResult.data = data;
        return jsonResult;
    }

    public static JsonResult<Void> fail(ServiceException e) {
        return fail(e.getServiceCode(),e.getMessage());
        //相当于
        //JsonResult jsonResult = new JsonResult();
        //jsonResult.state = e.getServiceCode.getValue();
        //jsonResult.message = e.getMessage();
        //return jsonResult
    }

    public static JsonResult<Void> fail(ServiceCode serviceCode, String message) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.state = serviceCode.getValue();
        jsonResult.message = message;
        return jsonResult;
    }
}
